/*
* © 2010 Autodata Solutions Company. All Rights Reserved
* This source code is the confidential and proprietary information of Autodata Solutions Company.
* The user shall not, in whole or in part, copy, publish, disclose or make any use of this source code
* without the prior written consent of Autodata Solutions Company.
*/
Ext.ns('net.autodata.compare.photos');
(function() {
	var DQ = Ext.DomQuery;
	
    var Store = Ext.extend(net.autodata.data.Store, {

        constructor: function(cfg) {
            cfg = cfg || {};

            Ext.apply(cfg, {
                autoLoad: false,
                reader: new Ext.data.JsonReader({
                    idProperty: 'imageId',
                    root: 'rows',
                    fields: [
						{ name: 'imageId' },
						{ name: 'acode' },
						{ name: 'shotId' },
						{ name: 'imageName' },
						{ name: 'imageType' }
					]
                })
            });

            if (!cfg.proxy) {
                cfg.proxy = new net.autodata.compare.data.photos.PhotosProxy();
            }

            Store.superclass.constructor.call(this, cfg);
        }        
    });

    /**
    * @class PhotosPanel
    * @extends Ext.BoxComponent
    * @namespace net.autodata.compare.photos
    */
    var Panel = Ext.extend(Ext.BoxComponent, {

        autoEl: {
            tag: 'div',
            cls: 'photos-panel'
        },
        
        width: 788,
        height: 598,
        view: undefined,

        emptyText: '',
        
        photoSelector: undefined,
        vehiclePhotos: undefined,
        
        viewBodySelector: '.photos-view',
        
        viewBody: undefined,
        emptyBody: undefined,

        store: undefined,

        baseVehicle: undefined,
        competitors: undefined,

        constructor: function(cfg) {
            cfg = cfg || {};
            var storeCfg = cfg.storeCfg;
            delete cfg.storeCfg;

            this.store = new Store(storeCfg);
            Panel.superclass.constructor.call(this, cfg);
        },

        initComponent: function() {
            Panel.superclass.initComponent.apply(this, arguments);
            var view = this.getView();
            view.init(this);
            
            this.emptyBody = new Ext.BoxComponent({
            	autoEl: {
            		tag: 'div',
            		cls: 'photospanel-emptybody'
            	},
            	html: '<div class="empty-text">' + this.emptyText + '</div>',
            	hideMode: 'display',
            	hidden: true
            });
            
            this.photoSelector = new net.autodata.compare.photos.PhotoSelectorPanel({
                listeners: {
                    'photoselected': this.onThumbSelected,
                    scope: this
                }
            });

            this.vehiclePhotos = new net.autodata.compare.photos.VehiclePhotosPanel();

            var store = this.getStore();
            store.on('load', this.onLoad, this);
        },

        /**
        * Supply the vehicles this panel is supposed to display and trigger the load
        * @method setVehicles
        * @param {Vehicle[]} vehicles Array of Vehicle objects (Base/Competitor)
        */
        setVehicles: function(baseVehicle, competitors) {
            if (!baseVehicle) {
                throw 'The baseVehicle parameter cannot be null';
            }

            this.baseVehicle = baseVehicle;
            this.competitors = competitors;

            //load the store
            var acodes = [baseVehicle.acode];
            Ext.each(this.competitors, function(v) {
                if (v) {
                    acodes.push(v.acode ? v.acode : '');
                }
            }, this);

            if (acodes.length > 0) {
                this.getStore().load({ params: { acodes: acodes} });
            }
        },

        /**
        * Finding the matching vehicle information for the given acode
        * @param {String} acode
        * @return {Vehicle} Undefined if no match is found
        */
        getVehicle: function(acode) {
            if (this.baseVehicle.acode === acode) {
                return this.baseVehicle;
            }

            for (var i = 0; i < this.competitors.length; i++) {
                var competitor = this.competitors[i];
                if (competitor && competitor.acode === acode) {
                    return competitor;
                }
            }

            return undefined;
        },

        getStore: function() {
            return this.store;
        },

        getView: function() {
            if (!this.view) {
                this.view = new net.autodata.compare.photos.PhotosView(this.viewCfg);
            }
            return this.view;
        },

        onRender: function() {
            Panel.superclass.onRender.apply(this, arguments);
            var view = this.getView();
            view.render();
            
            this.viewBody = Ext.get(DQ.selectNode(this.viewBodySelector, this.el.dom));
            this.viewBody.setVisibilityMode(Ext.Element.DISPLAY);
            
            this.emptyBody.render(this.el);
        },

        /**
        * @method onLoad
        * @private
        */
        onLoad: function(store, records) {
            //load thumbnails		
            if (records.length < 1) {
                //TODO clear out the selector's store
                return;
            }

            var baseAcode = this.baseVehicle.acode;
            var baseRecords = store.getRawData('acode', baseAcode);
            
            var hasRecords = baseRecords.length > 0;            
            this.viewBody[hasRecords ? 'show' : 'hide']();
            this.emptyBody[hasRecords ? 'hide' : 'show']();
            
            if (hasRecords) {
            	this.photoSelector.getStore().loadData(baseRecords.getRange(), false);
            }
        },

        /**
        * @param {Object} imgInfo Object containing the IOF Image information
        * @private
        */
        onThumbSelected: function(imgInfo) {
            //Create a resultset to load into the VehiclePhotos panel
            var store = this.getStore();

            var strId = '{0}-{1}-{2}';
            var shotId = imgInfo.shotId;
            var imageType = imgInfo.imageType;

            function getRecord(acode) {
                var record = store.getById(String.format(strId, acode, shotId, imageType));
                return record ? record.json : {};
            }

            var records = [getRecord(this.baseVehicle.acode)];

            Ext.each(this.competitors, function(competitor) {
                records.push(competitor ? getRecord(competitor.acode) : {});
            });

            this.vehiclePhotos.getStore().loadData({ rows: records });
        },

        /**
        * @private
        */
        onDestroy: function() {
            var store = this.getStore();
            store.un('load', this.onLoad, this);

            this.photoSelector.un('photoselected', this.onThumbSelected, this);

            Panel.superclass.onDestroy.apply(this, arguments);
        }

    });

    net.autodata.compare.photos.PhotosPanel = Panel;

})();